//
//  AllocationViewController.m
//  Lovely Food
//
//  Created by 李经纬 on 15/12/2.
//  Copyright © 2015年 李经纬. All rights reserved.
//

#import "AllocationViewController.h"
#import "ChoosePictureTableViewCell.h"
#import "AboutMeTableViewCell.h"
#import <AVOSCloud.h>
#import "UIImageView+WebCache.h"
#import "GenderTableViewController.h"
#import "ProvinceTableViewController.h"
#import "ChooseCityTableViewController.h"
#import "PhoneViewController.h"
#import "SignatureViewController.h"

@interface AllocationViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) NSMutableArray *fixedDataArray;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) AVUser *currentUser;

@end

@implementation AllocationViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fixedDataArray = [NSMutableArray arrayWithCapacity:10];
    self.currentUser = [AVUser currentUser];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    self.navigationItem.title = @"设置";

    // 注册xib
    UINib *nib = [UINib nibWithNibName:@"ChoosePictureTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"choose_Cell"];
    
    UINib *nib1 = [UINib nibWithNibName:@"AboutMeTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"aboutMe_Cell"];
    
    NSMutableArray *array = @[@"touxiang"].mutableCopy;
    NSMutableArray *arraySecond = @[@"关注", @"性别", @"地区",@"手机号"].mutableCopy;
    NSMutableArray *arrayName = @[@"个性签名"].mutableCopy;
    self.fixedDataArray = @[array, arraySecond, arrayName].mutableCopy;
    self.dataArray = @[@"follow",@"gender", @"address",@"phone"].mutableCopy;
    

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.fixedDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.fixedDataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    
    if (indexPath.section == 0) {
        ChoosePictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"choose_Cell" forIndexPath:indexPath];
       
        cell.myHeadImage.userInteractionEnabled = YES;

        AVFile *imageFile = [self.currentUser objectForKey:@"headImage"];
        [cell.myHeadImage sd_setImageWithURL:[NSURL URLWithString:imageFile.url] placeholderImage:[UIImage imageNamed:@"touxiang"]];

        

        
        cell.userLable.text = self.currentUser.username;
        cell.myHeadImage.layer.cornerRadius = 45;
        cell.myHeadImage.layer.masksToBounds = YES;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        return cell;
        
    } else {
        AboutMeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aboutMe_Cell" forIndexPath:indexPath];
        if (indexPath.section == 2 ) {
            cell.contentLabel.text = [self.currentUser objectForKey:@"sdasd"];
            cell.contentLabel.numberOfLines = 0;
            cell.contentLabel.lineBreakMode = NSLineBreakByCharWrapping;
            [cell.contentLabel sizeToFit];
        } else {
            cell.contentLabel.text = [self.currentUser objectForKey:self.dataArray[indexPath.row]];
        }
        cell.titleLabel.text = self.fixedDataArray[indexPath.section][indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    
}
// 点击功能
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 头像更换
    if (indexPath.section == 0) {
        // 创建
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        // 允许编辑
        picker.allowsEditing = YES;
        // 数据源
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        // 性别更换
        GenderTableViewController *genderTC = [[GenderTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
        genderTC.navigationItem.title = self.fixedDataArray[indexPath.section][indexPath.row];
        genderTC.gender = ^(NSString *str){
            
            [self.currentUser setObject:str forKey:@"gender"];
            [self.currentUser saveInBackground];
            [self.tableView reloadData];
            
        
        };
        
        [self showViewController:genderTC sender:nil];
        
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        // 地址更换
        ProvinceTableViewController * provinceTC = [[ProvinceTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
        provinceTC.navigationItem.title = self.fixedDataArray[indexPath.section][indexPath.row];
        [self showViewController:provinceTC sender:nil];
    } else if (indexPath.section == 1 && indexPath.row == 3) {
        // 手机号更换
        PhoneViewController *phoneVC = [[PhoneViewController alloc] init];
        phoneVC.navigationItem.title = self.fixedDataArray[indexPath.section][indexPath.row];
        phoneVC.phoneStr = [self.currentUser objectForKey:@"phone"];
        
        [self showViewController:phoneVC sender:nil];
    } else if (indexPath.section == 2) {
        // 个性签名更换
        SignatureViewController *signatureVC = [[SignatureViewController alloc] init];
        signatureVC.navigationItem.title = self.fixedDataArray[indexPath.section][indexPath.row];
        signatureVC.str = [self.currentUser objectForKey:@"sdasd"];
        [self showViewController:signatureVC sender:nil];
        
    }
    
}
// 获取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *i = info[UIImagePickerControllerEditedImage];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    ChoosePictureTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    cell.myHeadImage.image = i;
//    NSData *dataImage = UIImagePNGRepresentation(i);
    float kCompressionQuality = 0.1;
    NSData *dataImage = UIImageJPEGRepresentation(i, kCompressionQuality);
    AVFile *imageFile = [AVFile fileWithName:@"image.png" data:dataImage];
    [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"成功");
            // 获取本地用户信息
            AVUser *currentUser = [AVUser currentUser];
            
            [currentUser setObject:imageFile forKey:@"headImage"];
            [cell.myHeadImage sd_setImageWithURL:[NSURL URLWithString:imageFile.url] placeholderImage:[UIImage imageNamed:@"touxiang"]];
            //    [user setObject:imageFile forKey:@"attached"];
            //    [user save];
            [currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    NSLog(@"成功");
                    NSLog(@"%@",[currentUser objectForKey:@"headImage"]);
                    
                } else {
                    NSLog(@"%@",error);
                }
            }];
            
            
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
            
        }
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 100;
    }
    return 50;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
